package com.jic.market.impl.rest.lottery;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.utils.DateUtils;
import com.jic.market.common.util.BeanUtil;
import com.jic.market.common.util.Collections3;
import com.jic.market.entity.*;
import com.jic.market.entity.coupon.CouponConfig;
import com.jic.market.enums.*;
import com.jic.market.exception.BussinessException;
import com.jic.market.exception.LotteryDrawException;
import com.jic.market.mapper.*;
import com.jic.market.mapper.coupon.CouponConfigMapper;
import com.jic.market.request.manager.lottery.LotteryDrawRecordRequest;
import com.jic.market.request.rest.coupon.CouponReceiveOfPersonRequest;
import com.jic.market.request.rest.lottery.LotteryActivityInfoRestRequest;
import com.jic.market.request.rest.lottery.LotteryReceiverRequest;
import com.jic.market.request.rest.lottery.LotteryThemRestRequest;
import com.jic.market.request.rest.lottery.WinningRecordsRestRequest;
import com.jic.market.response.manager.lottery.LotteryDrawRecordResponse;
import com.jic.market.response.rest.lottery.*;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.rest.coupon.CouponRestService;
import com.jic.market.service.rest.lottery.LotteryActivityInfoRestService;
import com.jic.member.api.rest.MemberIntegralConsumerApi;
import com.jic.member.request.MememberIntegralActionRequest;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 抽奖活动奖品关联表
 * @author :
 * @email :
 * @since : 2020-03-03 03:05:46
 * @version : v1.0.0
 */
@Service
@Slf4j
public class LotteryActivityInfoRestServiceImpl implements LotteryActivityInfoRestService {

    @Autowired
    private LotteryThemeMapper lotteryThemeMapper;

    @Autowired
    private LotteryTypeMapper lotteryTypeMapper;

    @Autowired
    private LotteryAwardsMapper lotteryAwardsMapper;

    @Autowired
    private LotteryDrawRecordMapper lotteryDrawRecordMapper;

    @Autowired
    private LotteryDrawLimitMapper lotteryDrawLimitMapper;

    @Autowired
    private LotteryWinningLimitMapper lotteryWinningLimitMapper;

    @Autowired
    private LotteryReceiverMapper lotteryReceiverMapper;

    @Resource
    private ProductListApi productListApi;

    @Autowired
    private LargeTurntableTemplateEntityMapper largeTurntableTemplateEntityMapper;

    @Autowired
    private DiscountOrderDetailMapper discountOrderDetailMapper;

    @Resource
    private CouponConfigMapper couponConfigMapper;

    @Resource
    private CouponRestService couponRestService;

    @Resource
    private MemberIntegralConsumerApi memberIntegralConsumer;

    //是否返回模板信息配置
    public static final int PAGE_TEMP_1 = 1;

    public static final int PAGE_TEMP_2 = 2;


    @Override
    public LotteryActivityInfoRestResponse queryAwardsListByThemeCode(LotteryActivityInfoRestRequest request, int type) {

        LotteryActivityInfoRestResponse result;
        LotteryThemRestRequest lotteryThemRestRequest = new LotteryThemRestRequest();
        lotteryThemRestRequest.setPromotionCode(request.getPromotionCode());
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPromotionCode(lotteryThemRestRequest);
        log.info("查询抽奖，lotteryTheme={}", lotteryTheme);
        result = queryLotteryActivityInfoByCode(lotteryTheme, type);

        Date now = new Date();
        if(result.getStartTime().before(now) && result.getEndTime().after(now)){
            result.setStatus(LotteryConstant.THEME_STATUS_IN_PROGRESS);
        }else if(result.getStartTime().after(now)){
            result.setStatus(LotteryConstant.THEME_STATUS_NOT_STARTED);
        }else if(result.getEndTime().before(now)){
            result.setStatus(LotteryConstant.THEME_STATUS_ENDED);
        }else{
            result.setStatus(LotteryConstant.THEME_STATUS_NOT_STARTED);
        }
        //根据活动类型计算可用抽奖次数
        if(LotteryActivityTypeEnum.LOTTERY_ACTIVITY_TYPE_POINTS.getType().equals(result.getThemeType())  && request.getThirdUserId() != null){
            LotteryDrawLimit drawLimitPOExample = new LotteryDrawLimit();
            drawLimitPOExample.setMemberId(Long.valueOf(request.getThirdUserId()));
            //TODO 插入活动ID
            drawLimitPOExample.setThemeRefId(lotteryTheme.getId());
            drawLimitPOExample.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES);
            try {
                List<LotteryDrawLimit> drawLimitRecords = lotteryDrawLimitMapper.query(drawLimitPOExample);
                if(CollectionUtils.isNotEmpty(drawLimitRecords)){
                    LotteryDrawLimit drawLimitRecord = drawLimitRecords.get(0);
                    Long leftFreeChance = drawLimitRecord.getLimitBarrier() - drawLimitRecord.getConsumedNums();
                    leftFreeChance = leftFreeChance > 0 ? leftFreeChance : 0;
                    result.setFreeDrawNum(leftFreeChance);
                }
            } catch (Exception e) {
                log.error("查询免积分抽奖次数出错，themeId={}", request.getPromotionCode());
            }
        }

        //用户剩余可抽奖次数
        Long usableTimes = result.getFreeDrawNum() == null ? 0L : result.getFreeDrawNum();
        //用户每日抽奖限制次数
        Long dailyLimitNum = request.getThirdUserId() == null ? 0 : getRedDrawLimitNum(Long.valueOf(request.getThirdUserId()), lotteryTheme.getId(), result.getUsableNum());


        //TODO 获取用户积分数量
        Integer integral = 0;
        if (null != request.getThirdUserId()) {
            // 查询积分总数
            try {
                integral = memberIntegralConsumer.getMemberIntegralInfo(request.getThirdUserId());
                result.setPointAmount(null != integral ? integral.longValue() : 0L);
            }catch (Exception e){
                throw new LotteryDrawException(LotteryResultCodeDict.LOTTERY_USER_INTEGRAL_ERROR.getCode(),LotteryResultCodeDict.LOTTERY_USER_INTEGRAL_ERROR.getMsg());
            }
        }


        String channelCode = null;
        // 判断活动类型，若是引流活动则需要根据积分计算剩余可抽奖次数
        //TODO 获取用户积分数量 引流活动需要根据积分计算剩余可抽奖次数
        if (LotteryConstant.LOTTERY_TYPE_WITH_POINTS.equals(result.getThemeType())) {
            Long usablePointAmount = null != integral ? integral.longValue() : 0L;
            //按积分换算，可抽奖次数 = 总可用积分 / 单次抽奖消耗积分
            if(usablePointAmount != null && usablePointAmount >= 0L){
                if(result.getConsumeNum() != null){
                    //用int除，默认向下取整
                    if(result.getConsumeNum() >0L){
                        usableTimes += usablePointAmount.intValue() / result.getConsumeNum().intValue();
                    }else{
                        usableTimes += usablePointAmount.intValue();
                    }
                }else{
                    log.error("积分抽奖未设置积分消耗数量 活动ID:{}", request.getPromotionCode());
                }
            }

        } else if (LotteryConstant.LOTTERY_TYPE_WITH_ORDER.equals(result.getThemeType())) {
            if(request.getThirdUserId() != null){
                DiscountOrderDetail inputDTO = new DiscountOrderDetail();
                inputDTO.setThirdUserId(request.getThirdUserId());
                inputDTO.setCreateTimeStart(result.getStartTime());
                inputDTO.setCreateTimeEnd(result.getEndTime());
                List<DiscountOrderDetail> orderList = discountOrderDetailMapper.query(inputDTO);
                if(CollectionUtils.isEmpty(orderList)){
                    usableTimes = 0L;
                    result.setEffectiveOrderDrawNum(0L);
                }else{
                    if(CollectionUtils.isNotEmpty(orderList)){

                        List<String> validOrderList = new ArrayList<String>();

                        Long orderCount = 0L;
                        // 订单抽奖类型
                        Integer orderDrawType = result.getOrderDrawType();
                        BigDecimal orderDrawAmount = result.getOrderDrawAmount();
                        BigDecimal totalOrderActualAmount = BigDecimal.ZERO;
                        List<String> orderCodes = new ArrayList<>();
                        for(DiscountOrderDetail orderResultDTO : orderList){
                            // 获取订单实付金额
                            BigDecimal orderActualAmount = orderResultDTO.getPayAmount();
                            orderCodes.add(orderResultDTO.getOrderNo());
                            int singleAttendTimes = 0;
                            // 单订单满多少元
                            if (LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_SINGLE_MONEY.equals(orderDrawType)
                                    && orderDrawAmount != null) {
                                singleAttendTimes = orderActualAmount.compareTo(orderDrawAmount) >= 0 ? 1 : 0;
                                if (singleAttendTimes > 0) {
                                    //仅支付订单
                                    if (LotteryConstant.LOTTERY_ORDER_DRAW_MODAL_PAID.equals(result.getOrderDrawModel())) {
                                        if (orderResultDTO.getDiscountOrderStatus() == LotteryConstant.ORDER_PAYMENT_STATUS_2) {
                                            orderCount += singleAttendTimes;
                                            validOrderList.add(orderResultDTO.getOrderNo());
                                        }
                                    } else {
                                        orderCount += singleAttendTimes;
                                        validOrderList.add(orderResultDTO.getOrderNo());
                                    }
                                }
                            } else {
                                // 累计订单中金额
                                //仅支付订单
                                if (LotteryConstant.LOTTERY_ORDER_DRAW_MODAL_PAID.equals(result.getOrderDrawModel())) {
                                    if (orderResultDTO.getDiscountOrderStatus() == LotteryConstant.ORDER_PAYMENT_STATUS_2) {
                                        totalOrderActualAmount = totalOrderActualAmount.add(orderActualAmount);
                                    }
                                } else {
                                    totalOrderActualAmount = totalOrderActualAmount.add(orderActualAmount);
                                }
                            }
                        }
                        int totalTimes = 0;
                        // 累计金额
                        if ((LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_PER_MONEY.equals(orderDrawType) ||
                                LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_TOTAL_MONEY.equals(orderDrawType))
                                && orderDrawAmount != null) {
                            totalTimes = getTotalTimes(orderDrawType, orderDrawAmount, totalOrderActualAmount);
                            if (totalTimes > 0) {
                                orderCount += totalTimes;
                                validOrderList.addAll(orderCodes);
                            }
                        }

                        if(CollectionUtils.isNotEmpty(validOrderList)){
                            if(result.getDrawTimesPerOrder() != null){
                                usableTimes = orderCount * result.getDrawTimesPerOrder();
                            }else{
                                usableTimes = orderCount;
                            }

                            int usedTimes = 0;
                            try {
                                LotteryDrawRecordRequest drawRecordPOExample = new LotteryDrawRecordRequest();
                                drawRecordPOExample.setMemberId(Long.valueOf(request.getThirdUserId()));
                                drawRecordPOExample.setThemeRefId(lotteryTheme.getId());
                                usedTimes = (int) lotteryDrawRecordMapper.queryPageCount(drawRecordPOExample);
                            } catch (Exception e) {
                                log.error("查询抽奖记录异常，themeId={}", request.getPromotionCode());
                                throw new LotteryDrawException(LotteryResultCodeDict.QUERY_DRAW_RECORD_FALI.getCode(),LotteryResultCodeDict.QUERY_DRAW_RECORD_FALI.getMsg());
                            }

                            usableTimes -= usedTimes;
                        }
                        result.setEffectiveOrderDrawNum(usableTimes);
                    }
                }
            }
        }

        if(dailyLimitNum != null){
            usableTimes = dailyLimitNum == -1 ? usableTimes : Math.min((usableTimes == null || usableTimes < 0) ? 0 : usableTimes, dailyLimitNum);
        }

        result.setUsableNum(usableTimes);

        List<LotteryReceiveDetailVO> receiveList = queryLotteryReceiveDetail(request,lotteryTheme.getId());
        result.setReceiveList(receiveList);


        return result;
    }


    /**
     * 构造抽奖主题活动信息
     * @param lotteryTheme
     * @return
     */
    private LotteryActivityInfoRestResponse queryLotteryActivityInfoByCode(LotteryTheme lotteryTheme,int type){
        LotteryActivityInfoRestResponse lotteryActivityInfoRestResponse = new LotteryActivityInfoRestResponse();

        if(null==lotteryTheme){
            log.error("查不到抽奖活动信息");
            throw new LotteryDrawException(LotteryResultCodeDict.LOTTERY_THEME_NOT_FOUND.getCode(),LotteryResultCodeDict.LOTTERY_THEME_NOT_FOUND.getMsg());
        }
        if(StringUtils.isNotEmpty(lotteryTheme.getPageDescJson()) && PAGE_TEMP_2 == type){
            lotteryActivityInfoRestResponse.setPageDescJson(JSONObject.parseObject(lotteryTheme.getPageDescJson()));
            lotteryActivityInfoRestResponse.setActivityRule(lotteryTheme.getActivityRule());
            lotteryActivityInfoRestResponse.setAndroidLink(lotteryTheme.getAndroidLink());
            lotteryActivityInfoRestResponse.setIosLink(lotteryTheme.getIosLink());
            lotteryActivityInfoRestResponse.setH5Link(lotteryTheme.getH5Link());
        }

        lotteryActivityInfoRestResponse.setStatus(lotteryTheme.getStatus());
        lotteryActivityInfoRestResponse.setStartTime(lotteryTheme.getEffStartTime());
        lotteryActivityInfoRestResponse.setStartTimeStr(null!=lotteryTheme.getEffStartTime() ? DateFormatUtils.format(lotteryTheme.getEffStartTime(), "yyyy-MM-dd") : "");
        lotteryActivityInfoRestResponse.setEndTime(lotteryTheme.getEffEndTime());
        lotteryActivityInfoRestResponse.setEndTimeStr(null!=lotteryTheme.getEffEndTime() ? DateFormatUtils.format(lotteryTheme.getEffStartTime(), "yyyy-MM-dd") : "");

        //每日抽奖次数限制
        lotteryActivityInfoRestResponse.setAmountNum(lotteryTheme.getDailyDrawTimesLimit());
        lotteryActivityInfoRestResponse.setUsableNum(lotteryTheme.getDailyDrawTimesLimit());

        List<LotteryAwardsRestResponse> lotteryAwardsResponseList  = lotteryAwardsMapper.queryByThemeRefIdRest(lotteryTheme.getId());
        if (CollectionUtils.isEmpty(lotteryAwardsResponseList)) {
            log.error("查询当前抽奖活动下奖品信息为null");
            throw new LotteryDrawException(LotteryResultCodeDict.QUERY_AWARD_INFO_ERROR.getCode(),LotteryResultCodeDict.QUERY_AWARD_INFO_ERROR.getMsg());
        }
        lotteryActivityInfoRestResponse.setAwardsList(lotteryAwardsResponseList);

        LotteryType lotteryType = lotteryTypeMapper.queryByThemeRefId(lotteryTheme.getId());
        if(null == lotteryType){
            log.error("查询抽奖活动类型信息异常",lotteryTheme.getPromotionCode());
        }
        lotteryActivityInfoRestResponse.setThemeType(lotteryType.getType());
        //引流抽奖 积分消耗数
        lotteryActivityInfoRestResponse.setConsumeNum(lotteryType.getDrawPointsPerTime());
        //免积分抽奖次数
        lotteryActivityInfoRestResponse.setFreeDrawNum(null == lotteryType.getCostFreeDrawTimes() ? 0L : lotteryType.getCostFreeDrawTimes());
        // 每个订单抽奖次数
        lotteryActivityInfoRestResponse.setDrawTimesPerOrder(lotteryType.getDrawTimesPerOrder());
        // 订单抽奖节点 默认抽奖完成
        lotteryActivityInfoRestResponse.setOrderDrawModel(2);
        // 订单抽奖类型 1：单笔满X元  2：每消费满X元  3：累计消费满X元(仅交易抽奖)
        lotteryActivityInfoRestResponse.setOrderDrawType(lotteryType.getOrderDrawType());
        // 订单抽奖类型对应的金额
        lotteryActivityInfoRestResponse.setOrderDrawAmount(lotteryType.getOrderDrawAmount());

        // 设置缓存
//        LotteryCache.setObject(keyPrefix, result,LotteryCacheKey.LOTTERY_THEME_CACHE_DB_KEY.getExpireMins());
        return lotteryActivityInfoRestResponse;
    }


    private Long getRedDrawLimitNum(Long userId, Long activityId, Long defaultDailyLimit) throws LotteryDrawException{
        Long limitNum = -1L;
        try {
            LotteryDrawLimit drawLimitPOExample = new LotteryDrawLimit();
            drawLimitPOExample.setThemeRefId(activityId);
            drawLimitPOExample.setMemberId(userId);

            List<LotteryDrawLimit> drawLimitPOList = lotteryDrawLimitMapper.query(drawLimitPOExample);
            if(CollectionUtils.isNotEmpty(drawLimitPOList)){
                Long minLimitNum = null;//无限制记录
                Long leftFreeChances = 0L;//无限制记录
                for(LotteryDrawLimit drawLimitPO : drawLimitPOList){
                    if(drawLimitPO.getLimitType() == 1){
                        //总数限制
                        Long tempLimitNum = drawLimitPO.getLimitBarrier() - drawLimitPO.getConsumedNums();
                        minLimitNum = minLimitNum == null ? tempLimitNum : Math.min(minLimitNum, tempLimitNum);
                    }else if(drawLimitPO.getLimitType() == 2){
                        //每日限制
                        Date today = new Date();
                        Date consumedDate = drawLimitPO.getConsumedDate();
                        if(DateUtils.isSameDay(today, consumedDate)){
                            Long tempLimitNum = drawLimitPO.getLimitBarrier() - drawLimitPO.getConsumedNums();

                            minLimitNum = minLimitNum == null ? tempLimitNum : Math.min(minLimitNum, tempLimitNum);
                        }
                    }
                }

                if(minLimitNum != null){
                    limitNum = minLimitNum;
                }
            }
        } catch (Exception e) {
            log.error("查询异常",e);
        }

        //默认规则限制次数
        if(limitNum == -1 && defaultDailyLimit != null){
            limitNum = defaultDailyLimit;
        }

        return limitNum;
    }

    /***
     * 查询领奖记录
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<LotteryReceiveDetailVO>  queryLotteryReceiveDetail(LotteryActivityInfoRestRequest request,Long lotteryThemeId){
        // 查询抽奖记录信息，倒序默认五十条 加三分钟缓存
        Integer pageNo = 1;
        Integer pageSize = 10;
        if (null == pageNo) {
            pageNo = LotteryConstant.DEFAULT_PAGENO;
        }
        if (null == pageSize) {
            pageSize = LotteryConstant.QUERY_DRAW_RECORD_NUM;
        }
//        String keyPrefix = LotteryCacheKey.LOTTERY_DRAW_RECORD_CACHE_DB_KEY.getKey(request.getPromotionCode(), SystemContext.getCompanyId());
//        List<LotteryReceiveDetailVO> receiveList = (List<LotteryReceiveDetailVO>) LotteryCache.getObject(keyPrefix);
        List<LotteryReceiveDetailVO> receiveList = new ArrayList<>();
        if (CollectionUtils.isEmpty(receiveList)) {
            LotteryDrawRecordRequest recordExample = new LotteryDrawRecordRequest();
            recordExample.setThemeRefId(lotteryThemeId);
            recordExample.setDrawResult(Long.valueOf(LotteryConstant.LOTTERY_DRAW_RESULT_WINNING));

            List<LotteryDrawRecordResponse> drawList = Lists.newArrayList();
            try {
                //自增ID 效果同create_time desc
                drawList = lotteryDrawRecordMapper.queryPage(LotteryConstant.QUERY_DRAW_RECORD_NUM_START,LotteryConstant.QUERY_DRAW_RECORD_NUM,recordExample);
            } catch (Exception e) {
                log.error("查询用户中奖记录列表信息异常", request.getPromotionCode(), e);
            }
            List<LotteryReceiveDetailVO> receiveDetailList = Lists.newArrayList();
            for (LotteryDrawRecordResponse drawRecord : drawList) {
                LotteryReceiveDetailVO detail = new LotteryReceiveDetailVO();
                detail.setName(drawRecord.getMemberName());
                detail.setAwardsId(drawRecord.getAwardsRefId());
                detail.setAwardsName(drawRecord.getAwardsRefName());
                detail.setUserId(drawRecord.getMemberId());
                detail.setRecordId(drawRecord.getRecieverRefId());
                receiveDetailList.add(detail);
            }
            // 设置缓存
//            LotteryCache.setObject(keyPrefix, receiveDetailList,LotteryCacheKey.LOTTERY_DRAW_RECORD_CACHE_DB_KEY.getExpireMins());
            return receiveDetailList;
        } else {
            int start = 0;
            int end = 0;
            if (null != pageNo && null != pageSize) {
                start = (pageNo - 1) * pageSize;
                end = pageNo * pageSize;
            }
            int total = receiveList.size();
            if (start >= total && end >= total) {
                return Lists.newArrayList();
            }
            if (start < total && end > total) {
                end = total;
            }
            List<LotteryReceiveDetailVO> receiveDetailList = receiveList.subList(start, end);
            return receiveDetailList;
        }
    }


    @Override
    public LotteryDrawRestResponse initiateLottery(LotteryActivityInfoRestRequest request) {

        LotteryDrawRestResponse response = new LotteryDrawRestResponse();
        StringBuffer orderCodeForDraw = new StringBuffer();
        Long userId = Long.valueOf(request.getThirdUserId());
        LotteryThemRestRequest lotteryThemRestRequest = new LotteryThemRestRequest();
        lotteryThemRestRequest.setPromotionCode(request.getPromotionCode());
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPromotionCode(lotteryThemRestRequest);
        // 过滤等级
//        Boolean gradeFlag = Boolean.FALSE;
//        if(StringUtils.isNotBlank(request.getThirdUserId()) && StringUtils.isNotBlank(request.getChannelCode())){
//            PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
//            promotionMemberGradeQ.setPromotionCode(lotteryTheme.getPromotionCode());
//            promotionMemberGradeQ.setDeleteFlag(false);
//            List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
//            gradeFlag = promotionMemberGradeService.checkPromotion(request.getThirdUserId(), request.getChannelCode(), lotteryTheme.getChannelCodes(), promotionMemberGradeList);
//        }
//        if(!gradeFlag){
//            response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_USER_GRADE.getCode());
//            response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_USER_GRADE.getMsg());
//            return response;
//        }
        response = drawBaseCheck(lotteryTheme,request.getThirdUserId(), orderCodeForDraw);
        response.setThemeId(lotteryTheme.getId());

        //TODO  这里获取锁

        try {
            if(response.isFreeDraw() || response.getDrawResultCode()==null){
                List<LotteryAwards> awardsPOList = lotteryAwardsMapper.query(new LotteryAwards(){{setThemeRefId(lotteryTheme.getId());}});
                Map<Long, LotteryAwards> lotteryAwardsPOMap = new HashMap<Long, LotteryAwards>();
                LotteryAwards defaultNotWinningAwards = null;
                log.info("DEBUG INFO : 1 - awardsPOList : {}", awardsPOList);
                List<Lottery.LotteryAward> lotteryAwardList = new ArrayList<Lottery.LotteryAward>();
                Lottery.LotteryAward award = null;
                if(CollectionUtils.isNotEmpty(awardsPOList)){
                    for(LotteryAwards awardsPO : awardsPOList){
                        Lottery.LotteryAward awardVO = new Lottery.LotteryAward();
                        awardVO.setId(awardsPO.getId());
                        awardVO.setAwardProbability(awardsPO.getWinningRate().doubleValue() / 100D);
                        lotteryAwardList.add(awardVO);

                        //选一个谢谢参与作为默认未中奖状态的奖项
                        if(defaultNotWinningAwards == null && awardsPO.getAwardsCategory() == 1){
                            defaultNotWinningAwards = awardsPO;
                        }
                    }
                    lotteryAwardsPOMap = awardsPOList.stream().collect(Collectors.toMap(LotteryAwards::getId, Function.identity()));
                    try {
                        Lottery inst = new Lottery(lotteryAwardList);
                        //抽奖
                        award = inst.lottery();
                        //执行一次抽奖操作，更新每日抽奖限制表
                        updateDailyDrawLimit(userId, lotteryTheme, response.isFreeDraw());
                    }catch (SQLException e){
                        log.error("更新抽奖限制信息出错");
                        response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getCode());
                        response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getMsg());
                        throw new LotteryDrawException("-1","更新抽奖限制信息出错");
                    }
                }

                //未中奖
                if(award == null){
                    response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getCode());
                    response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getMsg());
                }else{
                    log.info("DEBUG INFO : 2 - award.getId : {}", award.getId());
                    LotteryAwards winningAwards = lotteryAwardsPOMap.get(award.getId());

                    AwardsResponseVO awardsVO = new AwardsResponseVO();

                    //获取个人中奖次数限制
                    Long winningLimitNum = getWinningLimitNum(userId, lotteryTheme);

                    log.info("DEBUG INFO : 3 - lotteryAwardsPOMap:{}, winningAwards:{}, winningAwards.getAwardsCategory:{}", lotteryAwardsPOMap, winningAwards, winningAwards == null ? "+++winningAwards is null+++" : winningAwards.getAwardsCategory());

                    //谢谢参与 或者 达到个人中奖次数上限，则结果为 未中奖（谢谢参与）
                    if(winningAwards == null || winningLimitNum == 0L){
                        winningAwards = defaultNotWinningAwards;
                        response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getCode());
                        response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getMsg());
                    }else if (winningAwards.getAwardsCategory() == 1){
                        response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getCode());
                        response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getMsg());
                    }else{
                        response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING.getCode());
                        response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING.getMsg());
                        //线上商品需要校验商品有效性。如果无效，则视为未中奖
                        if (winningAwards.getAwardsCategory() == 2 && winningAwards.getAwardsRefId() != null) {
                            List<Long> awardMpIds = Collections.singletonList(StringUtils.isEmpty(winningAwards.getAwardsRefId()) ? 0L : Long.valueOf(winningAwards.getAwardsRefId()));

//                            List<GoodsSkuQueryResponse> goodsSkuList = goodsSkuMapper.queryBySkuIds(awardMpIds);
                            List<ProductStoreInfo> goodsSkuList = productListApi.queryProductBySpuId(new GoodsPageQueryRequest() {{
                                setSpuIds(awardMpIds);
                            }});
                            // 判断上下架
                            List<ProductStoreInfo> goodsSkuListByStatus = productListApi.queryProductBySpuId(new GoodsPageQueryRequest() {{
                                setSpuIds(awardMpIds);
                                setCanSale(1);
                            }});
                            if (CollectionUtils.isNotEmpty(goodsSkuList)) {
                                ProductStoreInfo awardProductBaseDTO = goodsSkuList.get(0);
                                //判断奖品是否是上架状态, 商品为空表示未上架
                                if (CollectionUtils.isEmpty(goodsSkuListByStatus)) {
                                    //商品未上架，则结果为未中奖
                                    winningAwards = defaultNotWinningAwards;
                                    response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getCode());
                                    response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getMsg());
                                }
                            } else {
                                //商品不存在，则结果为未中奖
                                winningAwards = defaultNotWinningAwards;
                                response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getCode());
                                response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getMsg());
                            }
                        }

                        //检查奖品数量上限 TODO  这里最好重构，应该在活动开始之后，就往drawLimit表插记录。还有下面的查询和更新，改成只用一条update
                        if(winningAwards.getWinningNum() != null && !winningAwards.getWinningNum().equals(0)){
                            LotteryDrawLimit drawLimitPOExample = new LotteryDrawLimit();
                            drawLimitPOExample.setThemeRefId(lotteryTheme.getId());
                            drawLimitPOExample.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_AWARDS_LIMIT);
                            drawLimitPOExample.setLimitRef(winningAwards.getId());

                            List<LotteryDrawLimit> drawLimitPOList = lotteryDrawLimitMapper.query(drawLimitPOExample);
                            if(CollectionUtils.isEmpty(drawLimitPOList)){
                                LotteryDrawLimit awardsLimitPO = new LotteryDrawLimit();
                                awardsLimitPO.setThemeRefId(lotteryTheme.getId());
                                awardsLimitPO.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_AWARDS_LIMIT);
                                awardsLimitPO.setLimitBarrier(winningAwards.getWinningNum());
                                awardsLimitPO.setMemberId(Long.valueOf(request.getThirdUserId()));
                                //消耗的次数按照单次抽奖动作计数，若是改成单次中奖数量计数，则需要替换成awardsLimitPO.getAwardsRefNum()
                                awardsLimitPO.setConsumedNums(1L);
                                awardsLimitPO.setLimitRef(winningAwards.getId());
                                lotteryDrawLimitMapper.insert(awardsLimitPO);
                            }else{
                                LotteryDrawLimit drawLimit = drawLimitPOList.get(0);
                                if(drawLimit.getLimitBarrier() - drawLimit.getConsumedNums() > 0){
                                    //消耗的次数按照单次抽奖动作计数，若是改成单次中奖数量计数，则需要替换成awardsLimitPO.getAwardsRefNum()
                                    drawLimit.setConsumedNums(drawLimit.getConsumedNums() + 1);
                                    lotteryDrawLimitMapper.update(drawLimit);
                                }else{
                                    response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getCode());
                                    response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING_THANKS.getMsg());

                                    //若超过活动设置的该奖项奖品数量，则设置为不中奖
                                    winningAwards = defaultNotWinningAwards;

                                    log.info("DEBUG INFO : 因奖品数量超过活动设置上限，返回未中奖 : 活动id{}，奖项id{}", lotteryTheme.getId(), award.getId());
                                }
                            }
                        }

                        //中奖之后，更新每日中奖次数限制信息
                        if(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING.getCode().equals(response.getDrawResultCode())){
                            try {
                                updateDailyWinningLimit(userId, lotteryTheme);
                            }catch (Exception e){
                                log.error("更新中奖限制信息出错");
                                response.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getCode());
                                response.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getMsg());
                                if(winningAwards != null){
                                    awardsVO.setId(winningAwards.getId());
                                    awardsVO.setAwardsType(winningAwards.getAwardsCategory());
                                    awardsVO.setAwardsId(winningAwards.getAwardsRefId());
                                }
                                response.setAwardsVO(awardsVO);

                                throw new LotteryDrawException("-1", "更新中奖限制信息出错");
                            }
                        }
                    }

                    if(winningAwards != null){
                        awardsVO.setId(winningAwards.getId());
                        awardsVO.setLevel(winningAwards.getAwardsLevel());
                        awardsVO.setAwardsId(winningAwards.getAwardsRefId());
                        awardsVO.setAwardsType(winningAwards.getAwardsCategory());
                        awardsVO.setAwardsName(winningAwards.getAwardsRefName());
                        awardsVO.setAwardsNum(winningAwards.getAwardsRefNum());
                        awardsVO.setPicUrl(winningAwards.getAwardsPicUrl());
                    }else{
                        log.error("获取奖项信息异常");
                        throw new LotteryDrawException("-1", "获取奖项信息异常");
                    }
                    response.setAwardsVO(awardsVO);
                }

                //保存结果
                LotteryDrawRecord drawRecordPO = new LotteryDrawRecord();
                drawRecordPO.setThemeRefId(response.getThemeId());
                drawRecordPO.setMemberId(userId);
    //            drawRecordPO.setMemberName(SystemContext.getUserName());
                drawRecordPO.setDrawTime(new Date());
                if (orderCodeForDraw != null && !StringUtils.isBlank(orderCodeForDraw.toString())) {
                    drawRecordPO.setRefOrderCode(orderCodeForDraw.toString());
                }
                drawRecordPO.setDrawResult(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_WINNING.getCode().equals(response.getDrawResultCode()) ? LotteryConstant.LOTTERY_DRAW_RESULT_WINNING : LotteryConstant.LOTTERY_DRAW_RESULT_NOT_WINNING);
                if(drawRecordPO.getDrawResult().equals(LotteryConstant.LOTTERY_DRAW_RESULT_WINNING)){
                    LotteryAwards winningAwards = lotteryAwardsPOMap.get(award.getId());
                    if(response.getAwardsVO() != null){
                        drawRecordPO.setAwardsLevel(winningAwards.getAwardsLevel());
                        drawRecordPO.setAwardsCategory(winningAwards.getAwardsCategory());
                        drawRecordPO.setAwardsName(winningAwards.getAwardsName());
                        drawRecordPO.setAwardsRefId(winningAwards.getAwardsRefId());
                        drawRecordPO.setAwardsRefName(winningAwards.getAwardsRefName());
                        drawRecordPO.setAwardsRefNum(winningAwards.getAwardsRefNum());
                        if(LotteryConstant.AWARDS_CATEGORY_PRODUCT.equals(winningAwards.getAwardsCategory())){//商品
                            drawRecordPO.setStatus(0);
                            drawRecordPO.setAwardsRefPicUrl(winningAwards.getAwardsPicUrl());
                        }else if(LotteryConstant.AWARDS_CATEGORY_POINT.equals(winningAwards.getAwardsCategory())){//积分
                            drawRecordPO.setStatus(1);
                            drawRecordPO.setAwardsRefPicUrl(winningAwards.getAwardsPicUrl());

                            //发放积分
                            //TODO 积分发放 会员中心
                            MememberIntegralActionRequest mememberIntegralActionRequest = new MememberIntegralActionRequest();
                            mememberIntegralActionRequest.setThirdUserId(request.getThirdUserId());
                            mememberIntegralActionRequest.setIntegral(new BigDecimal(winningAwards.getAwardsRefNum()));
                            mememberIntegralActionRequest.setChangeTypes(1);
                            mememberIntegralActionRequest.setDeptId(lotteryTheme.getDeptId());
                            RestResult restResult = memberIntegralConsumer.updMemberIntegralInfo(mememberIntegralActionRequest);
//                            pointRemoteService.addPointsByLotteryWinning(winningAwards.getAwardsRefNum(), themePO.getId());
                            if(null == restResult.getData()){
                                log.error("发放积分奖励出错");
                                // 发放积分失败，默认未中奖，不抛异常，重置抽奖结果和中奖记录
                                resetDrawRecordNotWinning(drawRecordPO);
                                resetDrawResultNotWinning(response);
                            }

                        }else if(LotteryConstant.AWARDS_CATEGORY_COUPON.equals(winningAwards.getAwardsCategory())){//优惠券
                            drawRecordPO.setStatus(1);
                            drawRecordPO.setAwardsRefPicUrl(winningAwards.getAwardsPicUrl());

                            //发放优惠券
                            try {
                                CouponReceiveOfPersonRequest couponReceiveOfPersonRequest = new CouponReceiveOfPersonRequest();
                                couponReceiveOfPersonRequest.setPromotionId(winningAwards.getAwardsRefId());
                                couponReceiveOfPersonRequest.setThirdUserId(userId.toString());
                                couponReceiveOfPersonRequest.setAdminOperate(new AdminOperate());
                                RestResult restResult  = couponRestService.receiveCoupon(couponReceiveOfPersonRequest);
                                if(restResult.getCode().equals("0000") && (Boolean) restResult.getData()){
                                    CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(couponReceiveOfPersonRequest.getPromotionId());
                                    response.getAwardsVO().setValidityDateFrom(couponConfig.getCouponUseStartTime());
                                    response.getAwardsVO().setValidityDateTo(couponConfig.getCouponUseEndTime());
                                }else{
                                    log.error("发放奖励优惠券出错",restResult.getMsg());
                                    resetDrawRecordNotWinning(drawRecordPO);
                                    resetDrawResultNotWinning(response);
                                }

                            } catch (Exception e) {
                                log.error("发放奖励优惠券出错", e);
                                // 发放优惠券失败，默认未中奖，不抛异常，重置抽奖结果和中奖记录
                                resetDrawRecordNotWinning(drawRecordPO);
                                resetDrawResultNotWinning(response);
                            }
                        }else{//线下奖品
                            drawRecordPO.setStatus(0);
                            drawRecordPO.setAwardsRefPicUrl(winningAwards.getAwardsPicUrl());
                        }
                    }
                }

                lotteryDrawRecordMapper.insert(drawRecordPO);
                response.setReceiveRecordId(drawRecordPO.getId());
            }
        } catch (Exception e) {
            log.error("抽奖异常,LotteryInputVO={}",JSON.toJSONString(request), e);
            throw new LotteryDrawException("-1", "抽奖异常");
            //设置未中奖，回退中奖记录
        } finally {
//            LotteryCache.unlockLotteryDrawLimit(inputVO.getThemeId(), inputVO.getUserId(), channelCode);
        }


        return response;
    }

    /**
     * 校验抽奖活动 及用户
     * @param themePO
     * @param userId
     * @param orderCodeForDraw
     * @return
     */
    public LotteryDrawRestResponse drawBaseCheck(LotteryTheme themePO, String userId, StringBuffer orderCodeForDraw){
        LotteryDrawRestResponse checkResult = new LotteryDrawRestResponse();
        if(themePO == null || (themePO.getStatus() != null && themePO.getStatus().intValue() != 5
                && themePO.getStatus().intValue() != 3 && themePO.getStatus().intValue() != 8)){
            checkResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_INVALID_ACTIVITY.getCode());
            checkResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_INVALID_ACTIVITY.getMsg());
        }else if(themePO.getStatus().intValue() == 3){
            checkResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_ACTIVITY_NOT_STARTED.getCode());
            checkResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_ACTIVITY_NOT_STARTED.getMsg());
        }else if(themePO.getStatus().intValue() == 8){
            checkResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_ACTIVITY_ALREADY_ENDED.getCode());
            checkResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_ACTIVITY_ALREADY_ENDED.getMsg());
        }else{
            Map<Integer, Long> limitNumMap = getDrawLimitNum(userId, themePO);

            //TODO 校验新老用户
//            checkResult = themeLimitCheck(userId, themePO.getId(), checkResult);

            //计算用户剩余可用抽奖次数
            //1. 免积分抽奖次数
            Long freeLeft = themePO.getCostFreeDrawTimes() == null ? 0L : themePO.getCostFreeDrawTimes();

            //2. 剩余可用免积分抽奖次数
            if(freeLeft != 0L && limitNumMap.get(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES) != null){
                freeLeft = Math.min(freeLeft, limitNumMap.get(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES));
            }

            //3. 剩余可用每日抽奖次数
            Long dailyLeft = limitNumMap.get(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY) == null ? themePO.getDailyDrawTimesLimit() : limitNumMap.get(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY).longValue();

            //优先使用免费抽奖次数
            if(freeLeft > 0L){
                checkResult.setIsCostFreeDraw(true);
            }else if(dailyLeft <= 0L){
                //剩余抽奖次数已用完
                checkResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_EXCEED_DAILY_DRAW_TIMES.getCode());
                checkResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_EXCEED_DAILY_DRAW_TIMES.getMsg());
            }else if(LotteryConstant.LOTTERY_TYPE_WITH_POINTS.equals(themePO.getLotteryType()) && !checkDrawConditionByType(userId, themePO, orderCodeForDraw)){
                checkResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NO_ENOUGH_POINTS.getCode());
                checkResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NO_ENOUGH_POINTS.getMsg());
            }else if(LotteryConstant.LOTTERY_TYPE_WITH_ORDER.equals(themePO.getLotteryType()) && !checkDrawConditionByType(userId, themePO, orderCodeForDraw)){
                checkResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NO_ORDER_RECORD.getCode());
                checkResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NO_ORDER_RECORD.getMsg());
            }
        }
        try {
            //TODO 检查渠道信息是否在活动内 暂不需要
//            boolean isChannelAvailable = mktThemeConfigReadManage.checkChannelCodeAvailable(MktConstant.REF_TYPE_LOTTERY, themePO.getId(), SystemContext.getCompanyId(),channelCode);
//            if (!isChannelAvailable) {
//                log.error("查不到抽奖活动,themePO = null,themeId={}",themePO.getId());
////                throw new LotteryManageException(LotteryResultCodeDict.LOTTERY_THEME_NOT_FOUND.getCode(),LotteryResultCodeDict.LOTTERY_THEME_NOT_FOUND.getMessage());
//            }
        } catch (BussinessException e) {
            log.error("查询渠道信息异常：", e);
//            throw new LotteryManageException(e.getErrorCode(), e.getMessage(), e);
        }
        return checkResult;
    }


    private boolean checkDrawConditionByType(String userId, LotteryTheme themePO, StringBuffer orderCodeForDraw) throws LotteryDrawException{
        boolean checkResult = false;
        // 渠道
//        String channelCode = ChannelUtils.getChannelCode();
        String channelCode = null;
        try {
            LotteryType typePOExample = new LotteryType();
            typePOExample.setThemeRefId(themePO.getId());

            List<LotteryType> lotteryTypePOList = lotteryTypeMapper.query(typePOExample);

            if(CollectionUtils.isNotEmpty(lotteryTypePOList)){
                //一个活动对应一种类型
                LotteryType lotteryTypePO = lotteryTypePOList.get(0);

                //引流抽奖（积分抽奖）
                if(lotteryTypePO.getType() != null && lotteryTypePO.getType().intValue() == LotteryActivityTypeEnum.LOTTERY_ACTIVITY_TYPE_POINTS.getType().intValue()){
                    Long drawPoints = lotteryTypePO.getDrawPointsPerTime();

                    long userPointAmount = 0L;
                    //TODO 积分扣减
                    Integer integral = memberIntegralConsumer.getMemberIntegralInfo(userId);
                    userPointAmount = null == integral ? 0L : integral;
                    if(Long.compare(userPointAmount,drawPoints) >= 0){
                        //这里减积分
//                        pointRemoteService.consumePointByLotteryDraw(drawPoints,themePO.getId());
                        MememberIntegralActionRequest mememberIntegralActionRequest = new MememberIntegralActionRequest();
                        mememberIntegralActionRequest.setThirdUserId(userId);
                        mememberIntegralActionRequest.setIntegral(new BigDecimal(drawPoints));
                        mememberIntegralActionRequest.setChangeTypes(2);
                        mememberIntegralActionRequest.setDeptId(themePO.getDeptId());
                        RestResult restResult = memberIntegralConsumer.updMemberIntegralInfo(mememberIntegralActionRequest);
                        if(null == restResult.getData()){
                            checkResult = false;
                            log.error("memberIntegralConsumer.updMemberIntegralInfo扣除积分出错");
                        }else {

                            checkResult = true;
                        }
                    }
                }else if(lotteryTypePO.getType() != null && lotteryTypePO.getType().intValue() == LotteryActivityTypeEnum.LOTTERY_ACTIVITY_TYPE_ORDER.getType().intValue()){
//                    QueryOrderInputDTO inputDTO = new QueryOrderInputDTO();
//                    inputDTO.setUserId(userId);
//                    inputDTO.setCreateTimeStart(themePO.getEffStartTime());
//                    inputDTO.setCreateTimeEnd(themePO.getEffEndTime());
//
//                    if(org.apache.commons.lang.StringUtils.isNotBlank(channelCode)){
//                        inputDTO.setSysSourceList(Lists.newArrayList(channelCode));
//                    }
                    DiscountOrderDetail orderDetail = new DiscountOrderDetail();
                    orderDetail.setThirdUserId(userId);
                    orderDetail.setCreateTimeStart(themePO.getEffStartTime());
                    orderDetail.setCreateTimeEnd(themePO.getEffEndTime());
                    int orderDrawModal = lotteryTypePO.getOrderDrawModel();

                    List<DiscountOrderDetail> userFrontOrderResultDTOList = discountOrderDetailMapper.query(orderDetail);
                    if(CollectionUtils.isNotEmpty(userFrontOrderResultDTOList)){
                        Long orderCount = 0L;
                        List<String> validOrderList = new ArrayList<String>();
                        // 订单抽奖类型
                        Integer orderDrawType = lotteryTypePO.getOrderDrawType();
                        BigDecimal orderDrawAmount = lotteryTypePO.getOrderDrawAmount();
                        BigDecimal totalOrderActualAmount = BigDecimal.ZERO;
                        List<String> orderCodes = new ArrayList<>();
                        for(DiscountOrderDetail orderResultDTO : userFrontOrderResultDTOList){
                            // 获取订单实付金额
                            BigDecimal orderActualAmount = orderResultDTO.getPayAmount();
                            orderCodes.add(orderResultDTO.getOrderNo());
                            int singleAttendTimes = 0;
                            // 单订单满多少元
                            if (LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_SINGLE_MONEY.equals(orderDrawType)
                                    && orderDrawAmount != null) {
                                singleAttendTimes = orderActualAmount.compareTo(orderDrawAmount) >= 0 ? 1 : 0;
                                if (singleAttendTimes > 0) {
                                    //仅支付订单
                                    if (LotteryConstant.LOTTERY_ORDER_DRAW_MODAL_PAID.equals(lotteryTypePO.getOrderDrawModel())) {
                                        if (orderResultDTO.getDiscountOrderStatus() == LotteryConstant.ORDER_PAYMENT_STATUS_3) {
                                            orderCount += singleAttendTimes;
                                            validOrderList.add(orderResultDTO.getOrderNo());
                                        }
                                    } else {
                                        orderCount += singleAttendTimes;
                                        validOrderList.add(orderResultDTO.getOrderNo());
                                    }
                                }
                            } else {
                                // 累计订单中金额
                                //仅支付订单
                                if (LotteryConstant.LOTTERY_ORDER_DRAW_MODAL_PAID.equals(lotteryTypePO.getOrderDrawModel())) {
                                    if (orderResultDTO.getDiscountOrderStatus() == LotteryConstant.ORDER_PAYMENT_STATUS_3) {
                                        totalOrderActualAmount = totalOrderActualAmount.add(orderActualAmount);
                                    }
                                } else {
                                    totalOrderActualAmount = totalOrderActualAmount.add(orderActualAmount);
                                }
                            }
                        }
                        int totalTimes = 0;
                        // 累计金额
                        if ((LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_PER_MONEY.equals(orderDrawType) ||
                                LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_TOTAL_MONEY.equals(orderDrawType))
                                && orderDrawAmount != null) {
                            totalTimes = getTotalTimes(orderDrawType, orderDrawAmount, totalOrderActualAmount);
                            if (totalTimes > 0) {
                                orderCount += totalTimes;
                                validOrderList.addAll(orderCodes);
                            }
                        }
                        Long usableTimes = 0L;
                        if(lotteryTypePO.getDrawTimesPerOrder() != null){
                            usableTimes = orderCount * lotteryTypePO.getDrawTimesPerOrder();
                        }else{
                            usableTimes = orderCount;
                        }

                        Long usedTimes = 0L;
                        LotteryDrawRecordRequest drawRecordPOExample = new LotteryDrawRecordRequest();
                        drawRecordPOExample.setMemberId(Long.valueOf(userId));
                        drawRecordPOExample.setThemeRefId(themePO.getId());
                        try {
                            usedTimes = lotteryDrawRecordMapper.queryPageCount(drawRecordPOExample);
                        } catch (Exception e) {
                            log.error("查询抽奖记录异常，themeId={}", themePO.getId());
                            throw new LotteryDrawException(LotteryResultCodeDict.QUERY_DRAW_RECORD_FALI.getCode(),LotteryResultCodeDict.QUERY_DRAW_RECORD_FALI.getMsg());
                        }

                        if(usableTimes - usedTimes > 0){
                            checkResult = true;

                            //选择一个订单用作此次抽奖
                            if(usedTimes != 0){
                                LotteryDrawRecord lotteryDrawRecord = BeanUtil.copy(drawRecordPOExample,LotteryDrawRecord.class);
                                List<LotteryDrawRecord> drawRecordsWithUsedOrder = lotteryDrawRecordMapper.query(lotteryDrawRecord);

                                //排除已抽过奖的订单
                                if(CollectionUtils.isNotEmpty(drawRecordsWithUsedOrder)){
                                    // 查询已抽过奖的订单，并且判断这个订单的抽奖次数，如果小于DrawTimesPerOrder，那么这个订单还可以抽奖，就以这个订单作为抽奖的订单
                                    Map<String, List<LotteryDrawRecord>> orderCode2DrawRecordsMap = Collections3.partitionByProperty(drawRecordsWithUsedOrder, "refOrderCode");
                                    for(DiscountOrderDetail selectOrder : userFrontOrderResultDTOList){
                                        List<LotteryDrawRecord> tmpLotteryDrawRecordList = orderCode2DrawRecordsMap.get(selectOrder.getOrderNo());
                                        if(CollectionUtils.isNotEmpty(tmpLotteryDrawRecordList)){
                                            int tmpOrderCodeRecordSize = tmpLotteryDrawRecordList.size();
                                            // 单次订单抽奖
                                            if(LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_SINGLE_MONEY.equals(orderDrawType)) {
                                                if (lotteryTypePO.getDrawTimesPerOrder() != null && lotteryTypePO.getDrawTimesPerOrder() > tmpOrderCodeRecordSize) {
                                                    orderCodeForDraw.append(selectOrder.getOrderNo());
                                                    break;
                                                }
                                            } else {
                                                orderCodeForDraw.append(selectOrder.getOrderNo());
                                                break;
                                            }
                                        }
                                    }
                                    if(StringUtils.isBlank(orderCodeForDraw.toString())){
                                        List<String> drawOrderCodes = Collections3.extractToList(drawRecordsWithUsedOrder, "refOrderCode");
                                        for (String orderCode : validOrderList) {
                                            if (!drawOrderCodes.contains(orderCode)) {
                                                orderCodeForDraw.append(orderCode);
                                                break;
                                            }
                                        }

                                    }
                                }else{
                                    orderCodeForDraw.append(validOrderList.get(0));
                                }
                            }else{
                                orderCodeForDraw.append(validOrderList.get(0));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("检查可用积分/订单异常", e);
        }

        return checkResult;
    }

    private int getTotalTimes(Integer orderDrawType, BigDecimal orderDrawAmount, BigDecimal totalOrderActualAmount) {
        int times = 0;
        if (LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_PER_MONEY.equals(orderDrawType)) {
            if (BigDecimal.ZERO.compareTo(orderDrawAmount) == 0) {
                return 0;
            }
            times = totalOrderActualAmount.divide(orderDrawAmount, 2, BigDecimal.ROUND_HALF_UP).intValue();
        } else if (LotteryConstant.LOTTERY_ORDER_DRAW_TYPE_TOTAL_MONEY.equals(orderDrawType)){
            if (totalOrderActualAmount.compareTo(orderDrawAmount) >= 0) {
                times = 1;
            }
        }
        return  times;
    }


    private void updateDailyDrawLimit(Long userId, LotteryTheme themePO, boolean isFreeDraw) throws SQLException{
        List<LotteryDrawLimit> initDrawLimitPOs = new ArrayList<LotteryDrawLimit>();
        //若当次是免费抽奖，则更新免费抽奖限制数
        if(isFreeDraw){
            LotteryDrawLimit freeDrawLimitPOExample = new LotteryDrawLimit();
            freeDrawLimitPOExample.setMemberId(userId);
            freeDrawLimitPOExample.setThemeRefId(themePO.getId());
            freeDrawLimitPOExample.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES);
            List<LotteryDrawLimit> freeDrawLimitRecords = lotteryDrawLimitMapper.query(freeDrawLimitPOExample);
            try{
                //更新免费抽奖次数
                if(CollectionUtils.isEmpty(freeDrawLimitRecords)){
                    LotteryDrawLimit limitPO = new LotteryDrawLimit();
                    limitPO.setThemeRefId(themePO.getId());
                    limitPO.setMemberId(userId);
                    limitPO.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES);
                    limitPO.setLimitBarrier(themePO.getCostFreeDrawTimes());
                    limitPO.setConsumedNums(1L);
                    initDrawLimitPOs.add(limitPO);
                }else{
                     LotteryDrawLimit existFreeDrawLimitRecord = freeDrawLimitRecords.get(0);
                     Long consumedFreeDrawNumAfterDraw = existFreeDrawLimitRecord.getConsumedNums() + 1L;
                     existFreeDrawLimitRecord.setConsumedNums(consumedFreeDrawNumAfterDraw);

                     LotteryDrawLimit updateFreeDrawLimitExp = new LotteryDrawLimit();
                     updateFreeDrawLimitExp.setId(existFreeDrawLimitRecord.getId());
                     updateFreeDrawLimitExp.setLimitBarrier(existFreeDrawLimitRecord.getLimitBarrier());
                     updateFreeDrawLimitExp.setConsumedNums(consumedFreeDrawNumAfterDraw);
                     lotteryDrawLimitMapper.update(updateFreeDrawLimitExp);
                }
            }catch (Exception e) {
                throw new LotteryDrawException(LotteryResultCodeDict.LOTTERY_DRAW_LIMIT_ERROR.getCode(), LotteryResultCodeDict.LOTTERY_DRAW_LIMIT_ERROR.getMsg());
            }
        }

        // 2:按天限制，更新每日限制抽奖次数（包含免积分抽奖次数）
        LotteryDrawLimit dailyDrawLimitPOExample = new LotteryDrawLimit();
        dailyDrawLimitPOExample.setMemberId(userId);
        dailyDrawLimitPOExample.setThemeRefId(themePO.getId());
        dailyDrawLimitPOExample.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY);
        //每日限制，仅获取当天的记录
        dailyDrawLimitPOExample.setCreateTimeTodayBetween(true);
        List<LotteryDrawLimit> dailyLimitRecords = lotteryDrawLimitMapper.query(dailyDrawLimitPOExample);

        if(CollectionUtils.isEmpty(dailyLimitRecords)){
            LotteryDrawLimit limitPO = new LotteryDrawLimit();
            limitPO.setThemeRefId(themePO.getId());
            limitPO.setMemberId(userId);
            //目前只有按天数限制
            limitPO.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY);
            limitPO.setLimitBarrier(themePO.getDailyDrawTimesLimit());
            limitPO.setConsumedNums(1L);
            limitPO.setConsumedDate(new Date());
//            limitPO.setCompanyId(SystemContext.getCompanyId());
            initDrawLimitPOs.add(limitPO);
        }else{
            LotteryDrawLimit existDailyLimitRecord = dailyLimitRecords.get(0);
            Long consumedNumAfterDraw = existDailyLimitRecord.getConsumedNums().intValue() + 1L;
            existDailyLimitRecord.setConsumedNums(consumedNumAfterDraw);

            LotteryDrawLimit updateDailyDrawLimitExp = new LotteryDrawLimit();
            updateDailyDrawLimitExp.setId(existDailyLimitRecord.getId());
            updateDailyDrawLimitExp.setConsumedNums(consumedNumAfterDraw);
            lotteryDrawLimitMapper.update(updateDailyDrawLimitExp);
        }

        if(CollectionUtils.isNotEmpty(initDrawLimitPOs)){
            lotteryDrawLimitMapper.foreachInsert(initDrawLimitPOs);
        }

    }


    private void updateDailyWinningLimit(Long userId, LotteryTheme themePO) throws SQLException{
        LotteryWinningLimit winningLimitPOExample = new LotteryWinningLimit();
        winningLimitPOExample.setMemberId(userId);
        winningLimitPOExample.setThemeRefId(themePO.getId());

        winningLimitPOExample.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY);
        winningLimitPOExample.setConsumedDateBetween(true);
        List<LotteryWinningLimit> winningLimitRecords = lotteryWinningLimitMapper.query(winningLimitPOExample);
        //更新每日中奖次数
        if(CollectionUtils.isEmpty(winningLimitRecords)){
            LotteryWinningLimit limitPO = new LotteryWinningLimit();
            limitPO.setThemeRefId(themePO.getId());
            limitPO.setMemberId(userId);
            limitPO.setLimitType(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY);
            limitPO.setLimitBarrier(themePO.getDailyWinningTimesLimit());
            limitPO.setWinningTimes(1L);
            limitPO.setConsumedDate(new Date());
            lotteryWinningLimitMapper.insert(limitPO);
        }else{
            LotteryWinningLimit existWinningLimitRecord = winningLimitRecords.get(0);
            Long winningTimesAfterDraw = existWinningLimitRecord.getWinningTimes() + 1L;
            existWinningLimitRecord.setWinningTimes(winningTimesAfterDraw);

            LotteryWinningLimit updateDailyWinningLimitExp = new LotteryWinningLimit();
            updateDailyWinningLimitExp.setId(existWinningLimitRecord.getId());
            updateDailyWinningLimitExp.setWinningTimes(winningTimesAfterDraw);
            lotteryWinningLimitMapper.update( updateDailyWinningLimitExp);
        }
    }

    // 重置抽奖结果为未中奖
    private void resetDrawResultNotWinning(LotteryDrawRestResponse drawResult) {
        drawResult.setAwardsVO(null);
        drawResult.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getCode());
        drawResult.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getMsg());
    }

    // 重置抽奖记录为未中奖
    private void resetDrawRecordNotWinning(LotteryDrawRecord drawRecordPO) {
        drawRecordPO.setDrawResult(LotteryConstant.LOTTERY_DRAW_RESULT_NOT_WINNING);
        drawRecordPO.setAwardsLevel(null);
        drawRecordPO.setAwardsCategory(null);
        drawRecordPO.setAwardsName(null);
        drawRecordPO.setAwardsRefId(null);
        drawRecordPO.setAwardsRefName(null);
        drawRecordPO.setAwardsRefNum(null);
        drawRecordPO.setStatus(null);
        drawRecordPO.setAwardsRefPicUrl(null);
    }


    /**
     * 获取抽奖中奖次数限制
     * @param userId
     * @param themePO
     * @return
     */
    private Long getWinningLimitNum(Long userId, LotteryTheme themePO){
        Long winingLimitNum = -1L;

        //无限制规则
        if(themePO.getDailyWinningTimesLimit() == null){
            return winingLimitNum;
        }

        LotteryWinningLimit winningLimit = new LotteryWinningLimit();
        winningLimit.setMemberId(userId);
        winningLimit.setThemeRefId(themePO.getId());
        List<LotteryWinningLimit> winningLimitPOList = lotteryWinningLimitMapper.query(winningLimit);

        if(CollectionUtils.isNotEmpty(winningLimitPOList)){
            Long minLimitNum = null;
            for(LotteryWinningLimit winningLimitPO : winningLimitPOList){
                //TODO constants
                if(winningLimitPO.getLimitType() == 1){
                    //总数限制
                    Long tempLimitNum = winningLimitPO.getLimitBarrier() - winningLimitPO.getWinningTimes();
                    tempLimitNum = Math.max(tempLimitNum, 0);
                    minLimitNum = minLimitNum == null ? tempLimitNum : Math.min(minLimitNum, tempLimitNum);
                }else if(winningLimitPO.getLimitType() == 2){
                    //每日限制
                    Date today = new Date();
                    Date consumedDate = winningLimitPO.getConsumedDate();
                    if(DateUtils.isSameDay(today, consumedDate)){
                        Long tempLimitNum = winningLimitPO.getLimitBarrier() - winningLimitPO.getWinningTimes();
                        tempLimitNum = tempLimitNum > 0L ? tempLimitNum : 0L;
                        minLimitNum = minLimitNum == null ? tempLimitNum : Math.min(minLimitNum, tempLimitNum);
                    }
                }
            }

            winingLimitNum = minLimitNum == null ? themePO.getDailyWinningTimesLimit() : minLimitNum;
        }

        return winingLimitNum;
    }

    /**
     * 校验用户抽奖限制
     * @param userId
     * @param themePO
     * @return
     */
    private Map<Integer, Long> getDrawLimitNum(String userId, LotteryTheme themePO) {
        Map<Integer, Long> limitTypeMap = new HashMap<Integer, Long>();
        try {
            LotteryDrawLimit drawLimitPOExample = new LotteryDrawLimit();
            drawLimitPOExample.setThemeRefId(themePO.getId());
            drawLimitPOExample.setMemberId(Long.valueOf(userId));

            List<LotteryDrawLimit> drawLimitPOList = lotteryDrawLimitMapper.query(drawLimitPOExample);
            if(CollectionUtils.isNotEmpty(drawLimitPOList)){
                for(LotteryDrawLimit drawLimitPO : drawLimitPOList){
                    if(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_NUM.equals(drawLimitPO.getLimitType())){
                        //总数限制
                        Long tempLimitNum = drawLimitPO.getLimitBarrier() - drawLimitPO.getConsumedNums();
                        limitTypeMap.put(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_NUM, tempLimitNum);
                    }else if(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY.equals(drawLimitPO.getLimitType())){
                        //每日限制
                        Date today = new Date();
                        Date consumedDate = drawLimitPO.getConsumedDate();
                        if(DateUtils.isSameDay(today, consumedDate)){
                            Long tempLimitNum = drawLimitPO.getLimitBarrier() - drawLimitPO.getConsumedNums();
                            limitTypeMap.put(LotteryConstant.LOTTERY_LIMIT_TYPE_BY_DAY, tempLimitNum);
                        }
                    }else if(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES.equals(drawLimitPO.getLimitType())){
                        //免费抽奖次数限制
                        Long leftFreeChances = drawLimitPO.getLimitBarrier() - drawLimitPO.getConsumedNums();

                        limitTypeMap.put(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES, leftFreeChances);
                    }
                }
            }else{//无免积分抽奖次数限制记录，则取规则中的限制数量
                limitTypeMap.put(LotteryConstant.LOTTERY_LIMIT_TYPE_FREE_TIMES, themePO.getCostFreeDrawTimes() == null ? 0 : themePO.getCostFreeDrawTimes());
            }
        } catch (Exception e) {
            log.error("获取活动限制信息出错", e);
        }

        return limitTypeMap;
    }


    /**
     * 我的抽奖记录 分页查询
     * @param request
     * @param pageQuery
     * @return
     */
    @Override
    public PageResult<LotteryWinningRecordsResponse> getUserDrawRecordList(WinningRecordsRestRequest request, Page pageQuery) {
        //TODO 第三方用户ID 和 memberId 问题待解
        LotteryThemRestRequest lotteryThemRestRequest = new LotteryThemRestRequest();
        lotteryThemRestRequest.setPromotionCode(request.getPromotionCode());
        lotteryThemRestRequest.setDeptIds(request.getAdminOperate().getDeptIds());
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPromotionCode(lotteryThemRestRequest);
        LotteryDrawRecordRequest lotteryDrawRecordRequest = new LotteryDrawRecordRequest();
        lotteryDrawRecordRequest.setThemeRefId(lotteryTheme.getId());
        lotteryDrawRecordRequest.setMemberId(request.getThirdUserId());
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<LotteryWinningRecordsResponse> list = lotteryDrawRecordMapper.getUserWinningRecord(startIndex, pageQuery.getLimit(), lotteryDrawRecordRequest);
        long count = lotteryDrawRecordMapper.getUserWinningRecordCount(lotteryDrawRecordRequest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 保存奖品领取地址
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<String> saveReceiverAddress(LotteryReceiverRequest request) {
        if(null == request.getDrawRecordRefId()){
            throw new LotteryDrawException(LotteryResultCodeDict.ILLEGAL_PARAM.getCode(), LotteryResultCodeDict.ILLEGAL_PARAM.getMsg());
        }
        //查询领取记录信息
        LotteryDrawRecord lotteryDrawRecord = new LotteryDrawRecord(){{
                setMemberId(Long.valueOf(request.getThirdUserId()));
                setId(request.getDrawRecordRefId());}};
        List<LotteryDrawRecord> drawList = lotteryDrawRecordMapper.query(lotteryDrawRecord);
        if(CollectionUtils.isEmpty(drawList)){
            log.error("查询用户领奖信息异常 LotteryDrawRecord = null,request={}", JSON.toJSONString(request));
            throw new LotteryDrawException(LotteryResultCodeDict.QUERY_DRAW_RECORD_FALI.getCode(), LotteryResultCodeDict.QUERY_DRAW_RECORD_FALI.getMsg());
        }
        LotteryDrawRecord record = drawList.get(0);
        if(LotteryCodeEnum.LOTTERY_RECEVIED_1.getStatus().equals(record.getStatus())){
            log.error("当前奖品已被领取,request={}",JSON.toJSONString(request));
            throw new LotteryDrawException(LotteryResultCodeDict.QUERY_LOTTERY_REVICED_INFO.getCode(), LotteryResultCodeDict.QUERY_LOTTERY_REVICED_INFO.getMsg());
        }
        if(LotteryCodeEnum.LOTTERY_RECEVIE_EXPRIRE_2.getStatus().equals(record.getStatus())){
            log.error("当前奖品已过期,request={}",JSON.toJSONString(request));
            throw new LotteryDrawException(LotteryResultCodeDict.QUERY_LOTTERY_REVICE_INFO_EXPIRE.getCode(), LotteryResultCodeDict.QUERY_LOTTERY_REVICE_INFO_EXPIRE.getMsg());
        }
        if(StringUtils.isBlank(request.getName()) || StringUtils.isBlank(request.getMobile())){
            throw new LotteryDrawException(LotteryResultCodeDict.QUERY_LOTTERY_REVICE_ADDRESS_ERROR.getCode(), LotteryResultCodeDict.QUERY_LOTTERY_REVICE_ADDRESS_ERROR.getMsg());
        }

        LotteryThemRestRequest lotteryThemRestRequest = new LotteryThemRestRequest();
        lotteryThemRestRequest.setPromotionCode(request.getPromotionCode());
        lotteryThemRestRequest.setDeptIds(request.getAdminOperate().getDeptIds());
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPromotionCode(lotteryThemRestRequest);
        if(null == lotteryTheme){
            throw new LotteryDrawException(LotteryResultCodeDict.LOTTERY_THEME_NOT_FOUND.getCode(), LotteryResultCodeDict.LOTTERY_THEME_NOT_FOUND.getMsg());
        }

        //插入领取记录lottery_receiver
        LotteryReceiver receiver = BeanUtil.copy(request,LotteryReceiver.class);
        Long lotteryReceiverId = null;
        try{
            receiver.setThemeRefId(lotteryTheme.getId());
            lotteryReceiverMapper.insert(receiver);
            lotteryReceiverId = receiver.getId();
        }catch (Exception e){
            log.error("新增领取奖品信息异常,receiver={}",JSON.toJSONString(receiver),e);
            throw new LotteryDrawException(LotteryResultCodeDict.INSERT_LOTTERY_RECEIVE_ERROR.getCode(), LotteryResultCodeDict.INSERT_LOTTERY_RECEIVE_ERROR.getMsg());
        }

        //需要更新lottery_draw_record 中商品领取状态
        record.setRecieverRefId(lotteryReceiverId);
        record.setStatus(LotteryCodeEnum.LOTTERY_RECEVIED_1.getStatus());
        try {
            lotteryDrawRecordMapper.update(record);
        } catch (Exception e) {
            log.error("更新领取奖品状态信息异常,record={}",JSON.toJSONString(record),e);
            throw new LotteryDrawException(LotteryResultCodeDict.UPDATE_DRAW_RECORD_FALI.getCode(), LotteryResultCodeDict.UPDATE_DRAW_RECORD_FALI.getMsg());
        }

        return RestResult.success("操作成功");
    }

    @Override
    public LotteryDrawRestResponse drawLotteryByTemp(LotteryActivityInfoRestRequest request) {
        //根据accessToken 获取用户信息
//        UccUserOutputDTO uccUserOutputDTO = managerConsumer.queryUserInfoByAccessToken(request.getAccessToken());
//        if(uccUserOutputDTO == null){
//            throw new LotteryDrawException(LotteryResultCodeDict.UCC_USER_QUERY_ERROR.getCode(), LotteryResultCodeDict.UCC_USER_QUERY_ERROR.getMsg());
//        }
//        request.setThirdUserId(uccUserOutputDTO.getId());
        return initiateLottery(request);
    }

    @Override
    public LotteryActivityInfoRestResponse lotteryInfoByTemp(LotteryActivityInfoRestRequest request) {
        //根据accessToken 获取用户信息
//        UccUserOutputDTO uccUserOutputDTO = managerConsumer.queryUserInfoByAccessToken(request.getAccessToken());
//        if(uccUserOutputDTO == null){
//            throw new LotteryDrawException(LotteryResultCodeDict.UCC_USER_QUERY_ERROR.getCode(), LotteryResultCodeDict.UCC_USER_QUERY_ERROR.getMsg());
//        }
//        request.setThirdUserId(uccUserOutputDTO.getId());
        request.setThirdUserId(request.getThirdUserId());
        return queryAwardsListByThemeCode(request, PAGE_TEMP_2);
    }


    public static void main(String[] args) {
        StringBuffer orderCodeForDraw = new StringBuffer();
        System.out.println(orderCodeForDraw);
    }
}
